from flask import session, render_template, current_app, jsonify

from info import constants
from info.models import User, Category, News
# 使用蓝图对象
from info.utils.response_code import RET
from . import news_blue


# 首页模板数据加载
@news_blue.route('/')
def index():
    # 尝试从redis数据库中查找用户id
    user_id = session.get('user_id')
    # 判断查询结果
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.err(e)

    #新闻分类数据显示
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.err(e)
        return jsonify(errno=RET.DBERR,errmsrg='数据显示错误')
    #判断查询结果
    if not categories:
        return jsonify(errno=RET.NODATA,errimg='新闻分类查询失败')
    #遍历新闻分类列表
    category_list = []
    for category in categories:
        category_list.append(category.to_dict())

    #新闻点击排行
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.err(e)
        return jsonify(errno=RET.DBERR,errimg='点击查询失败')
    if not news_list:
        return jsonify(errno=RET.DATAERR,errimg='没有查到新闻排行数据')

    news_click_list = []
    for news in news_list:
        news_click_list.append(news.to_dict())
    data = {
        'user_info': user.to_dict() if user else None,

     'news_click_list':news_click_list


    }

    return render_template('news/index.html', data=data)


# logo图标加载
@news_blue.route('/fivacon.ico')
def fivacon():
    # logo图标不是每次都加载，亲清楚缓存，退出后重新刷新加载
    # 使用current_app,调用flask内置函数，发送静态文件给浏览器，实现logo图标加载
    return current_app.send_static_file('news/fivacon.ico')
